package com.zh.juc.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @Author: zhanghuan
 * @date: 2022/10/21 18:38
 * @description: create it
 * 多线程并发调用一个类的初始化方法，如果未被初始化过，将执行初始化工作，要求只能被初始化一次，只有一个线程操作成功
 */
class MyResource {
    public volatile Boolean isInit = Boolean.FALSE;
    AtomicReferenceFieldUpdater<MyResource, Boolean> referenceFieldUpdater =
            AtomicReferenceFieldUpdater.newUpdater(MyResource.class, Boolean.class, "isInit");

    public void init(MyResource resource) {
        if (referenceFieldUpdater.compareAndSet(resource, Boolean.FALSE, Boolean.TRUE)) {
            System.out.println(Thread.currentThread().getName() + "\t" + "---start init");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t" + "---over init");

        } else {
            System.out.println(Thread.currentThread().getName() + "\t" + "---已经有线程在进行初始化工作");
        }
    }

}

public class AtomicReferenceFieldUpdaterDemo {
    public static void main(String[] args) {
        MyResource myResource = new MyResource();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                myResource.init(myResource);
            }, String.valueOf(i)).start();
        }

    }
}
